<template>
    <div class="p-2">
        <el-card shadow="never">
            <template #header>
                <div class="card-header">
                    <span>{{ pageTitle }}</span>
                    <el-button @click="goBack" link>返回列表</el-button>
                </div>
            </template>

            <el-form ref="paperFormRef" :model="form" :rules="rules" label-width="120px">
                <!-- 基本信息 -->
                <el-divider content-position="left">基本信息</el-divider>
                <el-form-item label="考试标题" prop="title">
                    <el-input v-model="form.title" placeholder="请输入考试标题" />
                </el-form-item>
                <el-form-item label="考试描述" prop="description">
                    <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入考试描述" />
                </el-form-item>
                <el-form-item label="开始时间" prop="startTime">
                    <el-date-picker clearable v-model="form.startTime" type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker clearable v-model="form.endTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="请选择结束时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="考试时长" prop="duration">
                    <el-input-number v-model="form.duration" :min="1" :max="1000" placeholder="请输入考试时长(分钟)" />
                </el-form-item>
                <el-form-item label="总分值" prop="totalScore">
                    <el-input-number v-model="form.totalScore" :min="0" :max="1000" placeholder="请输入总分值" />
                </el-form-item>
                <el-form-item label="及格分数" prop="passScore">
                    <el-input-number v-model="form.passScore" :min="0" :max="1000" placeholder="请输入及格分数" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>

                <!-- 试题管理 -->
                <el-divider content-position="left">试题管理</el-divider>
                <div class="mb-4">
                    <el-button type="primary" @click="openQuestionSelector">添加题目</el-button>
                    <el-button type="danger" :disabled="!selectedQuestions.length"
                        @click="removeSelectedQuestions">移除选中题目</el-button>
                </div>

                <!-- 试题列表 -->
                <el-table v-loading="questionsLoading" :data="examQuestionsList"
                    @selection-change="handleQuestionsSelectionChange">
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column label="序号" type="index" width="80" align="center" />
                    <el-table-column label="题目内容" align="center" prop="title" width="200">
                        <template #default="scope">
                            <ContentRenderer :content="scope.row.title" />
                        </template>
                    </el-table-column>
                    <el-table-column label="题目类型" align="center" prop="questionType" width="100">
                        <template #default="scope">
                            <dict-tag :options="questionTypeOptions" :value="scope.row.questionType" />
                        </template>
                    </el-table-column>
                    <el-table-column label="分值" align="center" prop="questionScore" width="140">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.questionScore" :min="0" :max="100" size="small"
                                @change="updateTotalScore" />
                        </template>
                    </el-table-column>
                    <el-table-column label="排序" align="center" prop="questionOrder" width="140">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.questionOrder" :min="1" :max="999" size="small" />
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="120">
                        <template #default="scope">
                            <el-button link type="primary" icon="Delete"
                                @click="removeQuestion(scope.$index)">移除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="mt-4 text-center">
                    <el-button type="primary" @click="submitForm">保存试卷</el-button>
                    <el-button @click="goBack">取消</el-button>
                </div>
            </el-form>
        </el-card>

        <!-- 题目选择器对话框 -->
        <el-dialog v-model="questionSelectorVisible" title="选择题目" width="800px" append-to-body>
            <div class="mb-3">
                <el-form :inline="true" :model="questionQueryParams">
                    <el-form-item label="题目内容">
                        <el-input v-model="questionQueryParams.title" placeholder="请输入题目内容" clearable />
                    </el-form-item>
                    <el-form-item label="题目类型">
                        <el-select v-model="questionQueryParams.questionType" placeholder="请选择题目类型" clearable>
                            <el-option v-for="dict in questionTypeOptions" :key="dict.value" :label="dict.label"
                                :value="dict.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="getQuestionsList">搜索</el-button>
                        <el-button @click="resetQuestionQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <el-table v-loading="questionsLoading" :data="questionsList"
                @selection-change="handleQuestionSelectorSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="题目内容" align="center" prop="title">
                    <template #default="scope">
                        <ContentRenderer :content="scope.row.title" />
                    </template>
                </el-table-column>
                <el-table-column label="题目类型" align="center" prop="questionType" width="100">
                    <template #default="scope">
                        <dict-tag :options="questionTypeOptions" :value="scope.row.questionType" />
                    </template>
                </el-table-column>
                <el-table-column label="难度" align="center" prop="difficulty" width="120">
                    <template #default="scope">
                        <el-rate :model-value="scope.row.difficulty" disabled />
                    </template>
                </el-table-column>
                <el-table-column label="分值" align="center" prop="score" width="80" />
            </el-table>

            <pagination v-show="questionTotal > 0" :total="questionTotal" v-model:page="questionQueryParams.pageNum"
                v-model:limit="questionQueryParams.pageSize" @pagination="getQuestionsList" />

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="confirmAddQuestions">确定</el-button>
                    <el-button @click="questionSelectorVisible = false">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="PaperEdit" lang="ts">
import { listQuestions } from '@/api/answer/questions';
import { QuestionsVO, QuestionsQuery } from '@/api/answer/questions/types';
import { getExams, addExams, updateExams } from '@/api/answer/exams';
import { ExamsVO, ExamsForm } from '@/api/answer/exams/types';
import { listExamQuestions, addExamQuestions, delExamQuestions } from '@/api/answer/examQuestions';
import { ExamQuestionsVO, ExamQuestionsForm } from '@/api/answer/examQuestions/types';
import ContentRenderer from '@/components/ContentRenderer/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();

// 页面标题
const pageTitle = ref('新增试卷');

// 表单引用
const paperFormRef = ref<ElFormInstance>();

// 按钮加载状态
const buttonLoading = ref(false);

// 试卷表单数据
const initFormData: ExamsForm = {
    examId: undefined,
    title: '',
    description: '',
    startTime: undefined,
    endTime: undefined,
    duration: 60,
    totalScore: 0,
    passScore: 0,
    status: 1
};

const form = ref<ExamsForm>({ ...initFormData });

// 表单验证规则
const rules = {
    title: [{ required: true, message: '考试标题不能为空', trigger: 'blur' }],
    description: [{ required: true, message: '考试描述不能为空', trigger: 'blur' }],
    startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
    endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
    duration: [{ required: true, message: '考试时长不能为空', trigger: 'blur' }],
    totalScore: [{ required: true, message: '总分值不能为空', trigger: 'blur' }],
    passScore: [{ required: true, message: '及格分数不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
};

// 题目类型选项
const questionTypeOptions = [
    { value: 'single_choice', label: '单选题' },
    { value: 'multiple_choice', label: '多选题' },
    { value: 'fill_blank', label: '填空题' },
    { value: 'true_false', label: '判断题' }
];

// 试卷题目列表
const examQuestionsList = ref<any[]>([]);
const questionsLoading = ref(false);
const selectedQuestions = ref<any[]>([]);

// 题目选择器相关
const questionSelectorVisible = ref(false);
const questionsList = ref<QuestionsVO[]>([]);
const questionTotal = ref(0);
const selectedQuestionIds = ref<(string | number)[]>([]);

// 题目查询参数
const questionQueryParams = reactive<QuestionsQuery>({
    pageNum: 1,
    pageSize: 10,
    title: undefined,
    questionType: undefined,
    params: {}
});

// 获取试卷详情
const getExamDetail = async (examId: string | number) => {
    try {
        const res = await getExams(examId);
        form.value = res.data;
        pageTitle.value = '编辑试卷';
        // 获取试卷题目列表
        // getExamQuestionsList(examId);

        examQuestionsList.value = res.data.questions

    } catch (error) {
        console.error('获取试卷详情失败', error);
    }
};

// 获取试卷题目列表
// const getExamQuestionsList = async (examId: string | number) => {
//     questionsLoading.value = true;
//     try {
//         const res = await listExamQuestions({ examId });
//         // 需要获取每个题目的详细信息
//         const questionPromises = res.rows.map(async (item: ExamQuestionsVO) => {
//             try {
//                 const questionRes = await proxy?.$http.get(`/answer/questions/${item.questionId}`);
//                 return {
//                     ...item,
//                     ...questionRes.data,
//                     questionScore: item.questionScore,
//                     questionOrder: item.questionOrder
//                 };
//             } catch (error) {
//                 console.error('获取题目详情失败', error);
//                 return item;
//             }
//         });

//         examQuestionsList.value = await Promise.all(questionPromises);
//         updateTotalScore();
//     } catch (error) {
//         console.error('获取试卷题目列表失败', error);
//     } finally {
//         questionsLoading.value = false;
//     }
// };

// 获取题目列表
const getQuestionsList = async () => {
    questionsLoading.value = true;
    try {
        const res = await listQuestions(questionQueryParams);
        questionsList.value = res.rows;
        questionTotal.value = res.total;
    } catch (error) {
        console.error('获取题目列表失败', error);
    } finally {
        questionsLoading.value = false;
    }
};

// 重置题目查询参数
const resetQuestionQuery = () => {
    questionQueryParams.title = undefined;
    questionQueryParams.questionType = undefined;
    questionQueryParams.pageNum = 1;
    getQuestionsList();
};

// 打开题目选择器
const openQuestionSelector = () => {
    questionSelectorVisible.value = true;
    getQuestionsList();
};

// 题目选择器选择变更
const handleQuestionSelectorSelectionChange = (selection: QuestionsVO[]) => {
    selectedQuestionIds.value = selection.map(item => item.questionId);
};

// 确认添加题目
const confirmAddQuestions = () => {
    if (selectedQuestionIds.value.length === 0) {
        proxy?.$modal.msgError('请选择题目');
        return;
    }

    // 获取选中的题目详情
    const selectedItems = questionsList.value.filter(item =>
        selectedQuestionIds.value.includes(item.questionId)
    );

    // 检查是否有重复题目
    const existingIds = examQuestionsList.value.map(item => item.questionId);
    const newItems = selectedItems.filter(item => !existingIds.includes(item.questionId));

    if (newItems.length === 0) {
        proxy?.$modal.msgWarning('所选题目已存在于试卷中');
        questionSelectorVisible.value = false;
        return;
    }

    // 添加新题目到试卷中
    const startOrder = examQuestionsList.value.length > 0
        ? Math.max(...examQuestionsList.value.map(item => item.questionOrder)) + 1
        : 1;

    newItems.forEach((item, index) => {
        examQuestionsList.value.push({
            ...item,
            questionScore: item.score || 0,
            questionOrder: startOrder + index
        });
    });

    updateTotalScore();
    questionSelectorVisible.value = false;
    proxy?.$modal.msgSuccess(`成功添加${newItems.length}道题目`);
};

// 试题列表选择变更
const handleQuestionsSelectionChange = (selection: any[]) => {
    selectedQuestions.value = selection;
};

// 移除选中题目
const removeSelectedQuestions = () => {
    if (selectedQuestions.value.length === 0) {
        return;
    }

    proxy?.$modal.confirm('确认移除所选题目吗？').then(() => {
        const selectedIds = selectedQuestions.value.map(item => item.questionId);
        examQuestionsList.value = examQuestionsList.value.filter(
            item => !selectedIds.includes(item.questionId)
        );
        updateTotalScore();
        proxy?.$modal.msgSuccess('移除成功');
    });
};

// 移除单个题目
const removeQuestion = (index: number) => {
    proxy?.$modal.confirm('确认移除该题目吗？').then(() => {
        examQuestionsList.value.splice(index, 1);
        updateTotalScore();
        proxy?.$modal.msgSuccess('移除成功');
    });
};

// 更新总分值
const updateTotalScore = () => {
    const total = examQuestionsList.value.reduce(
        (sum, item) => sum + (Number(item.questionScore) || 0),
        0
    );
    form.value.totalScore = total;
};

// 提交表单
const submitForm = () => {
    paperFormRef.value?.validate(async (valid: boolean) => {
        if (!valid) return;
        if (examQuestionsList.value.length === 0) {
            proxy?.$modal.msgError('请至少添加一道题目');
            return;
        }

        buttonLoading.value = true;
        try {

            const examQuestions = examQuestionsList.value.map(item => {
                return {
                    questionId: item.questionId,
                    questionOrder: item.questionOrder,
                    questionScore: item.questionScore
                }
            });

            form.value.questionCount = examQuestions.length;

            // 1. 保存试卷基本信息
            if (form.value.examId) {
                // 更新试卷
                await updateExams({
                    ...form.value,
                    examQuestions
                });
            } else {
                // 新增试卷
                const res = await addExams({
                    ...form.value,
                    examQuestions
                });
            }

            //   // 2. 如果是编辑模式，先删除原有题目关联
            //   if (form.value.examId) {
            //     await delExamQuestions(form.value.examId);
            //   }

            //   // 3. 添加新的题目关联
            //   const examQuestionsPromises = examQuestionsList.value.map(item => {
            //     const examQuestion: ExamQuestionsForm = {
            //       examId,
            //       questionId: item.questionId,
            //       questionOrder: item.questionOrder,
            //       questionScore: item.questionScore
            //     };
            //     return addExamQuestions(examQuestion);
            //   });

            //   await Promise.all(examQuestionsPromises);

            proxy?.$modal.msgSuccess('保存成功');
            goBack();
        } catch (error) {
            console.error('保存试卷失败', error);
            proxy?.$modal.msgError('保存失败，请重试');
        } finally {
            buttonLoading.value = false;
        }
    });
};

// 返回列表页
const goBack = () => {
    router.push('/answer/exams');
};

// 页面初始化
onMounted(() => {
    const examId = route.query.examId;
    if (examId) {
        getExamDetail(examId as string);
    }
});
</script>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>